$(function() {
    layui.use(['table', 'dropdown','form','laydate'], function(){
        var table = layui.table,
            form = layui.form ,
            laydate = layui.laydate ,
            $ = layui.$;

        let str = '';
        AjaxGet('/userAunt/seleProject').then(function (response){
            str += `<option value="">请选择</option>`;
            response.data.map(function (v){
                str += `<option value="${v.id}">${v.name}</option>`
            });
            $("#projectId").html(str)
            form.render('select');
        }).catch(function (error){
            layer.msg(error.msg)
        })
    laydate.render({
            elem: "#createTime",
            trigger: 'click',
            type: 'datetime'
        });
        // 创建渲染实例
        table.render({
            elem: '#exampleTable'
            ,id:'exampleTable'
            ,method:"POST"
            ,contentType: 'application/json'
            ,url: "/userInterview/backgroundList"
            ,cellMinWidth: 80
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                , curr: pages //设定初始在第 5 页
                , groups: 5 //只显示 1 个连续页码
                , limit : 15
                , limits : [15,30,50,100,200]
            }
            ,request:{
                pageName: 'pageNumber',
                limitName: 'pageSize'
            }
            ,where: {
                title:$("#title").val(),
                inviterName:$("#inviterName").val(),
                workAddress:$("#workAddress").val(),
                createTime:$("#createTime").val(),
                projectId:$("#projectId").val(),
                status:parseInt($("#status").val()),
                interviewStatus:parseInt($("#interviewStatus").val()),
            }
            ,defaultToolbar: false
            ,loading: false
            ,cols: [[
                {
                    field : 'title',
                    title : '标题',
                    align : 'center',
                    templet:d=>`<span>${d.title}</span>`
                },
                {
                    field : 'inviterName',
                    title : '邀约人',
                    align : 'center',
                    templet:d=>`<span>${d.inviterName}</span>`
                },
                {
                    field : 'inviterPhone',
                    title : '联系方式',
                    align : 'center',
                    templet:d=>`<span>${d.inviterPhone}</span>`
                },
                {
                    field: 'projectName',
                    title: '需求类型',
                    align: 'center',
                    // width:240,
                    templet: function (d) {
                        let str = '';
                        let projectName = d.projectName;
                        if ( projectName != null ){
                            projectName = projectName.split('、');
                            projectName.map(function (v,k){
                                if( v != '' ){
                                    if ( k <= 2) {
                                        str += v+'、';
                                    }
                                }
                            })
                            str=str.substring(0,str.length-1)
                            return `
							<span>${str}</span>
							`;
                        }else{
                            return '-';
                        }
                    }
                },

                {
                    field : 'inviteeName',
                    title : '被邀约人',
                    align : 'center',
                    templet:d=>`<span>${d.inviteeName}</span>`
                },
                {
                    field : 'inviteePhone',
                    title : '联系方式',
                    align : 'center',
                    templet:d=>`<span>${d.inviteePhone}</span>`
                },
                {
                    field : 'workAddress',
                    title : '工作地址',
                    align : 'center',
                    templet:d=>`<span>${d.workAddress}</span>`
                },
                {
                    field : 'status',
                    title : '当前状态',
                    align : 'center',
                    templet : function( d ) {
                        if (d.status == 1) {
                            return '<span class="label label-primary">已发送</span>';
                        } else if (d.status == 2) {
                            return '<span class="label label-warning">已取消</span>';
                        }else if (d.status == 3) {
                            return '<span class="label label-success">已同意</span>';
                        }else if (d.status == 4) {
                            return '<span class="label label-warning">已拒绝</span>';
                        }else{
                            return '<span>-</span>';
                        }

                    }
                },
                {
                    field : 'interviewStatus',
                    title : '面试状态',
                    align : 'center',
                    templet : function( d ) {
                        if (d.interviewStatus == 2) {
                            return '<span class="label label-primary">已结束</span>';
                        } else if (d.interviewStatus == 1) {
                            return '<span class="label label-warning">洽谈中</span>';
                        }else{
                            return '<span>-</span>';
                        }
                    }
                },
                {
                    field : 'result',
                    title : '面试结果',
                    align : 'center',
                    templet : function( d ) {
                        if (d.result == 0) {
                            return '<span class="label label-warning">待定</span>';
                        }else if (d.result == 1) {
                            return '<span class="label label-primary">面试通过</span>';
                        }else if (d.result == 2) {
                            return '<span class="label label-warning">面试拒绝</span>';
                        }else{
                            return '<span>-</span>';
                        }
                    }
                },
                {
                    field : 'updateTime',
                    title : '更新时间',
                    align : 'center',
                    templet:d=>`<span>${d.updateTime}</span>`
                },
                {
                    field : 'createTime',
                    title : '创建时间',
                    align : 'center',
                    templet:d=>`<span>${d.createTime}</span>`
                },
                {
                    title : '操作',
                    field : 'id',
                    align : 'center',
                    width:200,
                    templet : function(d) {
                        var e = '<a  class="btn btn-primary btn-sm '+s_info_h+' " href="#" mce_href="#" title="详情" onclick="lookInfo(\''
                            + d.demandId  + '\', \'' + d.inviteeId+'\' )"><i class="fa fa-send"></i></a> ';

                        var b1 = '<a  class="btn btn-primary btn-sm '+s_push_h+' " href="#" mce_href="#" title="邀约面试" onclick="push(\''
                            + d.demandId+'\' , \'' + d.inviteeId+'\' )"><i class="fa fa-arrow-circle-o-up"></i></a> ';

                        var b2 = '<a  class="btn btn-primary btn-sm '+s_edit_h+' " href="#" mce_href="#" title="编辑" onclick="edit(\''
                            + d.demandId+'\' , \'' + d.inviteeId+'\' )"><i class="fa fa-edit"></i></a> ';
                        var b3 = '<a  class="btn btn-primary btn-sm '+s_cancel_h+' " href="#" mce_href="#" title="取消" onclick="cancel(\''
                            + d.demandId+'\' , \'' + d.inviteeId+'\' )">' +
                            `<svg t="1724811885611" class="fa" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2006" width="12" height="12"><path d="M860.513821 211.460163c-1.24878-44.435772-37.879675-79.817886-82.107317-79.817887h-94.803252l-13.944715-34.549593-0.20813-0.520325c-5.723577-12.38374-18.315447-20.500813-32.052033-20.604878h-203.96748c-13.944715-0.104065-26.744715 7.908943-32.572357 20.604878L385.04065 131.121951H291.278049c-44.123577 0.936585-79.505691 36.214634-80.442277 80.442277V818.15935c0.312195 21.749593 9.469919 42.874797 25.079675 57.964227 15.609756 15.089431 36.943089 23.414634 58.692683 22.998374h483.902439c44.227642 0 80.858537-35.486179 82.107317-79.817886V211.772358l-0.104065-0.312195z m-432.078049-3.642277l27.681301-60.878049h159.635773l27.6813 60.878049H428.435772zM281.80813 817.430894V212.188618c0.312195-2.809756 1.665041-5.515447 3.746342-7.388618 2.289431-1.977236 5.099187-2.913821 8.117073-2.705691h61.918699l-11.863415 26.328455c-4.786992 9.990244-4.578862 21.853659 0.624391 31.635773 5.099187 9.886179 14.777236 16.858537 25.704065 18.627642l0.83252 0.104065h326.243902c12.17561 0.104065 23.518699-5.931707 30.178862-16.234146 6.660163-10.302439 7.596748-23.102439 2.497561-34.133334l-11.96748-26.43252h59.837399c2.913821-0.20813 5.931707 0.728455 8.117073 2.705691 2.185366 1.873171 3.538211 4.578862 3.746341 7.388618l0.520326 605.346341c-0.728455 5.827642-6.035772 10.198374-11.863415 9.678049H293.77561c-5.931707 0.520325-11.239024-3.850407-11.96748-9.678049z" p-id="2007" fill="#ffffff"></path><path d="M535.726829 350.803252C425.521951 350.803252 336.130081 440.195122 336.130081 550.4s89.39187 199.596748 199.596748 199.596748 199.596748-89.39187 199.596748-199.596748-89.39187-199.596748-199.596748-199.596748z m108.227643 254.022764c14.985366 14.985366 14.985366 39.336585 0 54.321951-14.985366 14.985366-39.336585 14.985366-54.321952 0l-54.321951-54.321951-54.321951 54.321951c-14.985366 14.985366-39.336585 14.985366-54.321951 0-14.985366-14.985366-14.985366-39.336585 0-54.321951l54.321951-54.321951-54.321951-54.321951c-14.985366-14.985366-14.985366-39.336585 0-54.321951 14.985366-14.985366 39.336585-14.985366 54.321951 0l54.321951 54.321951 54.321951-54.321951c7.180488-7.284553 16.962602-11.343089 27.160976-11.34309s19.980488 4.058537 27.160976 11.34309c15.297561 14.256911 16.234146 38.087805 2.28943 53.593496l-54.321951 54.321951 52.032521 55.050406z" fill="#ffffff" p-id="2008"></path></svg>`
                            +'</a> ';

                        var ss = '<a class="btn btn-success btn-sm '+s_remove_h+' " href="#" title="删除"  mce_href="#" onclick="remove(\''
                            + d.demandId+'\' , \'' + d.inviteeId+'\' )"><i class="fa fa-remove"></i></a>';
                        return    b1 + e +
                                  (d.status == null||d.status == 0||d.status == 4||d.result == 1||d.result == 2?'':
                                      (b2+(d.status==2?'':b3))
                                  )
                                 + ss;
                    }
                }
            ]]
            ,response: {
                statusCode: 0 //重新规定成功的状态码为 200，table 组件默认为 0
            }
            ,parseData: function(res){ //将原始数据解析成 table 组件所规定的数据
                if( res.code != 0 ){

                    return false;
                }

                if(Number(res.data.total)>0&&res.data.records.length==0){
                    pages--;
                    if(pages>0) {
                        table.reload('exampleTable', {
                            page: {curr: pages},
                            where: {
                                title:$("#title").val(),
                                inviterName:$("#inviterName").val(),
                                workAddress:$("#workAddress").val(),
                                createTime:$("#createTime").val(),
                                projectId:$("#projectId").val(),
                                status:parseInt($("#status").val()),
                                interviewStatus:parseInt($("#interviewStatus").val()),
                            }
                        })
                    }
                }

                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            }
            ,jump: function (obj, first) {
                //首次不执行
                if (!first) {
                    pages = obj.curr
                }
            }
            ,error: function(res, msg){

            }

            ,done: function (res){
                form.render()
                hindLoading()
            }
        });

        var $ = layui.$, active = {
            reload: function(){
                //执行重载
                table.reload('exampleTable', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: {
                        title:$("#title").val(),
                        inviterName:$("#inviterName").val(),
                        workAddress:$("#workAddress").val(),
                        createTime:$("#createTime").val(),
                        projectId:$("#projectId").val(),
                        status:parseInt($("#status").val()),
                        interviewStatus:parseInt($("#interviewStatus").val()),
                    }
                });
            }
        };
        form.on('switch(switchTest)', function(data){
            let id=$(data.othis[0].parentNode).find('input').attr('myid')
            var loadIndex = layer.load(0);
            AjaxPost('/userAunt/updateUserAnutStatus', {id,enableStatus:this.checked?'1':'0'}).then(function (response){
                parent.layer.msg("操作成功");
                layer.close(loadIndex)
                load();
            }).catch(error => {
                layer.msg(error.msg)
                layer.close(loadIndex)
                load();
            })




        })
        $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        //触发表格复选框选择
        table.on('checkbox(test)', function(obj){
            console.log(obj)
        });

        //触发表格单选框选择
        table.on('radio(test)', function(obj){
            console.log(obj)
        });

    });
});

var pages = 1;
/**
 * 所有的重置表格
 */
function load(){
    layui.use(['table'], ()=>{
        layui.table.reload('exampleTable',{
            where: {
                title:$("#title").val(),
                inviterName:$("#inviterName").val(),
                workAddress:$("#workAddress").val(),
                createTime:$("#createTime").val(),
                projectId:$("#projectId").val(),
                status:parseInt($("#status").val()),
                interviewStatus:parseInt($("#interviewStatus").val()),
            }
        })
    })
}

function lookInfo(demandId,inviteeId){
    let toIndex= layer.open({
        type: 2,
        title:'面试邀约详情',
        maxmin: true,
        shadeClose: false,
        area:['800px','500px'],
        content:  `/jzweb/jazUserDemand/backstage/interviewInvitation/info/${demandId}/${inviteeId}/info`
    });
    layer.full(toIndex);
}
// function edit(id){
//     let toIndex= layer.open({
//         type: 2,
//         title:'面试邀约详情',
//         maxmin: true,
//         shadeClose: false,
//         area:['800px','500px'],
//         content:  `/jzweb/jazUserDemand/backstage/interviewInvitation/info/${id}/edit`
//     });
//     layer.full(toIndex);
// }
function push(demandId,inviteeId){

    const toIndex=layer.open({
        type: 1,
        area: ['500px', '450px'],
        title: '面试邀约',
        shade: 0.6,
        shadeClose: false,
        maxmin: true,
        anim: 0,
        content: `
<form class="layui-form layui-form-pane" style="width: 100%;height: 100%;padding: 10px;" id="myForm">  
   <div class="layui-form-item"> 
      <label class="layui-form-label required">面试时间</label>
      <div class="layui-input-block">
        <input class="layui-input" placeholder="请选择" name="interviewTime" id="interviewTime" lay-verify="required"
                               autocomplete="off"> 
      </div>
   </div>
    <div class="layui-form-item"> 
      <label class="layui-form-label required">面试形式</label>
      <div class="layui-input-block">  
        <select id="interviewFormat" lay-search="" name="interviewFormat" lay-verify="required" lay-filter="aihao">
                            <option value="">请选择面试形式</option>
                            <option value="0">线下</option>
                            <option value="1">线上</option> 
        </select>
      </div>
   </div>
    <div class="layui-form-item showHide"> 
      <label class="layui-form-label required">面试地址</label>
      <div class="layui-input-block">
        <input class="layui-input" placeholder="请输入面试地址" name="interviewAddress"  style="display: none" >  
         <select  name="province" id="province" lay-filter="province"  class="layui-input" placeholder="请输入所属省份"></select>
         <select  name="city" id="city" lay-filter="city"  class="layui-input" placeholder="请输入所属市"></select>
         <select  name="area" id="area" lay-filter="area"  class="layui-input" placeholder="请输入所属区"></select>
        
      </div>
   </div>
    <div class="layui-form-item showHide"> 
      <label class="layui-form-label required">详细地址</label>
      <div class="layui-input-block">
        <input class="layui-input" placeholder="请输入详细地址" name="interviewAddressDetail" > 
      </div>
   </div>
    <div class="layui-form-item"> 
      <label class="layui-form-label">备注</label>
      <div class="layui-input-block">
        <input class="layui-input" placeholder="请输入备注" name="remark"> 
      </div>
   </div>
   
  <div class="layui-form-item" style="display: flex;    justify-content: center;">
    <button class="btn btn-success" type="button"  lay-submit lay-filter="layedit-code-yes">提交</button>
  </div>
</form> 
                `,
        success: (layero, index) => {
            //省市區
            Areainit("interviewAddress")
            layui.use(['form','laydate'], () => {
                var form = layui.form;
                form.render('select');

                let laydate=layui.laydate
                laydate.render({
                    elem: "#interviewTime",
                    min:(data=null)=>{
                        if(null==data){
                            data=new Date()
                        }
                        return data.getFullYear()+'-'+(data.getMonth()>9?(data.getMonth()+1):('0'+(data.getMonth()+1)))+'-'+data.getDate()
                    },
                    trigger: 'click',
                    type: 'datetime'
                });
                // select 事件
                form.on('select(aihao)', function(data){
                    for (let i = 0; i <  $(".showHide").length; i++) {
                        if( data.value=='1'){
                            $($(".showHide")[i]).hide()
                        }else{
                            $($(".showHide")[i]).show()
                        }
                    }

                });
                form.on('submit(layedit-code-yes)', (data) => {
                    const mydata = data.field
                    if(mydata.interviewFormat=='0'){
                        if(mydata.interviewAddress==''){
                            layer.msg('请输入面试地址')
                            return false
                        }
                        if(mydata.interviewAddressDetail==''){
                            layer.msg('请输入详细地址')
                            return false
                        }

                    }
                    console.log('提交数据',mydata)
                    mydata.demandId=demandId
                    mydata.inviteeId=inviteeId
                    layer.close(index)
                    load();
                    // //修改
                    $.ajax({
                        type: 'post',
                        data: JSON.stringify({
                            ...mydata
                        }),
                        contentType: 'application/json',
                        url: '/userInterview/backgroundInviteInterview',
                        success: function (r) {
                            if (r.code == 0) {
                                layer.msg(r.msg);
                                layer.close(index)
                                load();
                            } else {
                                layer.msg(r.msg);
                            }
                        }
                    });

                });
            })


        }
    });
    // layer.full(toIndex);
    // let toIndex= layer.open({
    //     type: 2,
    //     title:'面试推送',
    //     maxmin: true,
    //     shadeClose: false,
    //     area:['800px','500px'],
    //     content:  `/jzweb/jazUserDemand/backstage/interviewInvitation/info/${id}/push`
    // });
    // layer.full(toIndex);
}
function edit(demandId,inviteeId){

    const toIndex=layer.open({
        type: 1,
        area: ['500px', '450px'],
        title: '修改面试邀约',
        shade: 0.6,
        shadeClose: false,
        maxmin: true,
        anim: 0,
        content: `
<form class="layui-form layui-form-pane" style="width: 100%;height: 100%;padding: 10px;" id="myForm">  
   <div class="layui-form-item"> 
      <label class="layui-form-label required">面试时间</label>
      <div class="layui-input-block">
        <input class="layui-input" placeholder="请选择" name="interviewTime" id="interviewTime" lay-verify="required"
                               autocomplete="off"> 
      </div>
   </div>
    <div class="layui-form-item"> 
      <label class="layui-form-label required">面试形式</label>
      <div class="layui-input-block">  
        <select id="interviewFormat" lay-search="" name="interviewFormat" lay-verify="required" lay-filter="aihao">
                            <option value="">请选择面试形式</option>
                            <option value="0">线下</option>
                            <option value="1">线上</option> 
        </select>
      </div>
   </div>
    <div class="layui-form-item showHide"> 
      <label class="layui-form-label required">面试地址</label>
      <div class="layui-input-block">
         <input class="layui-input" placeholder="请输入面试地址" name="interviewAddress"  style="display: none" >  
         <select  name="province" id="province" lay-filter="province"  class="layui-input" placeholder="请输入所属省份"></select>
         <select  name="city" id="city" lay-filter="city"  class="layui-input" placeholder="请输入所属市"></select>
         <select  name="area" id="area" lay-filter="area"  class="layui-input" placeholder="请输入所属区"></select>
        
      </div>
   </div>
    <div class="layui-form-item showHide"> 
      <label class="layui-form-label required">详细地址</label>
      <div class="layui-input-block">
        <input class="layui-input" placeholder="请输入详细地址" id="interviewAddressDetail" name="interviewAddressDetail" > 
      </div>
   </div>
    <div class="layui-form-item"> 
      <label class="layui-form-label">备注</label>
      <div class="layui-input-block">
        <input class="layui-input" placeholder="请输入备注" id="remark" name="remark"> 
      </div>
   </div>
   
  <div class="layui-form-item" style="display: flex;    justify-content: center;">
    <button class="btn btn-success" type="button"  lay-submit lay-filter="layedit-code-yes">提交</button>
  </div>
</form> 
                `,
        success: (layero, index) => {
            //省市區

            layui.use(['form','laydate'], () => {
                var form = layui.form;
                $.ajax({
                    type: 'get',
                    data: {
                        demandId,
                        inviteeId
                    },
                    contentType: 'application/json',
                    url: '/userInterview/backgroundGetInterview',
                    success: function (r) {
                        if (r.code == 0) {
                            //设置数据
                            $('#interviewTime').val(r.data.interviewTime)
                            $('#interviewFormat').val(r.data.interviewFormat)
                            //
                            for (let i = 0; i <  $(".showHide").length; i++) {
                                if( r.data.interviewFormat+''=='1'){
                                    $($(".showHide")[i]).hide()
                                }else{
                                    $($(".showHide")[i]).show()
                                    let myLists= StrToList(r.data.interviewAddress)
                                    Areainit("interviewAddress",myLists)
                                    //StrToList
                                    // Areainit("interviewAddress",r.data.interviewAddress.split('-'))
                                    $('#interviewAddressDetail').val(myLists[myLists.length-1])
                                }
                            }
                            $('#remark').val(r.data.remark)
                            form.render('select');


                        } else {
                            layer.msg(r.msg);
                        }
                    }
                })
                form.render('select');


                let laydate=layui.laydate
                laydate.render({
                    elem: "#interviewTime",
                    min:(data=null)=>{
                        if(null==data){
                            data=new Date()
                        }
                        return data.getFullYear()+'-'+(data.getMonth()>9?(data.getMonth()+1):('0'+(data.getMonth()+1)))+'-'+data.getDate()
                    },
                    trigger: 'click',
                    type: 'datetime'
                });
                // select 事件
                form.on('select(aihao)', function(data){
                    for (let i = 0; i <  $(".showHide").length; i++) {
                        if( data.value=='1'){
                            $($(".showHide")[i]).hide()
                        }else{
                            $($(".showHide")[i]).show()
                            Areainit("interviewAddress")
                        }
                    }

                });
                form.on('submit(layedit-code-yes)', (data) => {
                    const mydata = data.field
                    if(mydata.interviewFormat=='0'){
                        if(mydata.interviewAddress==''){
                            layer.msg('请输入面试地址')
                            return false
                        }
                        if(mydata.interviewAddressDetail==''){
                            layer.msg('请输入详细地址')
                            return false
                        }

                    }
                    console.log('提交数据',mydata)
                    mydata.demandId=demandId
                    mydata.inviteeId=inviteeId
                    // //修改
                    $.ajax({
                        type: 'post',
                        data: JSON.stringify({
                            ...mydata
                        }),
                        contentType: 'application/json',
                        url: '/userInterview/backgroundEditInterview',
                        success: function (r) {
                            if (r.code == 0) {
                                layer.msg(r.msg);
                                layer.close(index)
                                load();
                            } else {
                                layer.msg(r.msg);
                            }
                        }
                    });

                });
            })


        }
    });
}

function remove(demandId,inviteeId) {

    layer.confirm('确定要删除选中的记录？', {
        title: '删除',
        btn : [ '确定', '取消' ]
    }, function() {
        $.ajax({
            url : '/userInterview/backgroundDeleted',
            type : "post",
            data : {
                 demandId,
                inviteeId
            },
            success : function(r) {
                if (r.code==0) {
                    layer.msg(r.msg);
                    load();
                }else{
                    layer.msg(r.msg);
                }
            }
        });
    })
}
function cancel(demandId,inviteeId) {

    layer.confirm('确定要取消邀约？', {
        title: '取消邀约',
        btn : [ '确定', '取消' ]
    }, function() {
        $.ajax({
            url : '/userInterview/backgroundCancelInterview',
            type : "post",
            data :{
                 demandId,
                inviteeId
            },
            success : function(r) {
                if (r.code==0) {
                    layer.msg(r.msg);
                    load();
                }else{
                    layer.msg(r.msg);
                }
            }
        });
    })
}